from sys import stderr
from argparse import ArgumentParser, Namespace
from typing import Any, Callable, Optional, Sequence
from drek.business import show_info, init_dot_directory, backup_directories_of_interest, list_keys  # type: ignore


def get_mode_options() -> list:
    return [
        "help",
        "info",
        "backup",
    ]


def get_description() -> str:
    return (
        "drek helps manage secrets and identities. "
        "It discourages remote passwords, uses zero-knowledge proofs, "
        "and supports self-sovereign identity!"
    )


def get_mode_options_help() -> None:
    print("modes:")
    for option in get_mode_options():
        print(f"  {option}")


def get_parser() -> ArgumentParser:
    parser = ArgumentParser(description=get_description())
    parser.add_argument(
        "-o", "--output", help="Output path",
    )
    parser.add_argument(
        "mode",
        metavar="mode",
        help="Modes of operation",
        choices=get_mode_options(),
        type=str.lower,
        nargs="?",
        default=None,
    )
    parser.add_argument(
        "commands", help="Mode commands", nargs="*", default=None,
    )
    return parser


def process_with_argparsed(args: Namespace, help_func: Callable) -> None:
    init_dot_directory()

    if args.mode == "help" and args.commands:
        if args.commands[0] == "info":
            print("drek info")
            print("Show details about the current system.")
        else:
            help_func()
    elif args.mode == "info":
        show_info()
        list_keys()
    elif args.mode == "backup":
        if args.output:
            backup_directories_of_interest(args.output)
        else:
            print("drek: backup requires an output path", file=stderr)
            help_func()
    else:
        # print("miss")
        # print(args.mode)
        # print(args.commands)
        help_func()
        get_mode_options_help()


def client_parse_args(parser: ArgumentParser, args: Optional[Sequence[str]]) -> None:
    process_with_argparsed(
        parser.parse_args(args), parser.print_help,
    )


def get_foo(args: dict) -> Optional[Sequence[str]]:
    return args[1:]


def client_main(args: dict) -> None:
    client_parse_args(get_parser(), get_foo(args))
